import { defineStore } from 'pinia';

import { dict } from '@/api/system/dict';
import { DictData } from '@/api/system/dict/types';
import { ResultEnum } from '@/enums/httpEnum';
import { I18N, I18N_TAG, SEX } from '@/constants/dictTypes';
import i18n from '@/i18n';



export const useDictStore = defineStore('dict', {
  state: () => ({
    dictCache: new Map<string, Array<DictData>>(),
  }),
  getters: {
    getDictCache: (state) => {
      return state.dictCache;
    },
  },
  actions: {
    /**
     * 字典翻译
     * @param dictType 字典类型
     * @param dictValue 字典值
     * @returns
     */
    async toLabel(dictType: string,dictValue:string|number): Promise<string> {
      const dictArrayData:Array<DictData> = await this.dictFunction(dictType);
      return dictArrayData.find(item=>item.dictValue==dictValue).dictLabel
    },
    /**
     * 国际化性别字典数据
     * @returns
     */
    async sexDictHook(): Promise<DictData[]> {
      return this.dictFunction(SEX);
    },
    /**
     * 国际化语言字典数据
     * @returns
     */
    async i18nDictHook(): Promise<DictData[]> {
      return this.dictFunction(I18N);
    },

    /**
     * 国际化标签字典数据
     * @returns
     */
    async i18nTagDictHook(): Promise<DictData[]> {
      return this.dictFunction(I18N_TAG);
    },

    /**
     * 字典函数通用方法
     * @param key 对应字典的字典key
     * @returns 字典集合
     */
    async dictFunction(key: string): Promise<DictData[]> {
      const cache = this.dictCache.get(key);
      if (cache) {
        console.debug('cache');
        return cache;
      }
      const { code, result } = await dict(key);
      if (ResultEnum.SUCCESS === code) {
        this.dictCache.set(key, result);
        return result;
      }
      return [];
    },
  },
});
